package com.jianbo.proxy.util;

import java.util.LinkedHashMap;

import org.noear.snack.ONode;
import org.noear.snack.core.TypeRef;

public class JsonUtil {
    
     /**
     * 解析 json 为 map (有序)
     * @param <T>
     * @param json
     * @return
     */
    public static <T> LinkedHashMap<String, T> parseSortMap(String json) {
        TypeRef<LinkedHashMap<String, T>> typeRef = new TypeRef<LinkedHashMap<String, T>>(){};
        try {
            LinkedHashMap<String, T> result = ONode.deserialize(json, typeRef.getClass());
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> LinkedHashMap<String, T> parseSortMap(String json, Class<T> clazz) {
        try {
            ONode onode = ONode.load(json);
            LinkedHashMap<String, T> map = new LinkedHashMap<>();
            for(String name : onode.obj().keySet()) {
                ONode item = onode.obj().get(name);
                T object = item.toObject(clazz);
                map.put(name, object);
            }
            return map;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String toJson(Object object) {
        return ONode.stringify(object);
    }
}
